import { createSlice } from "@reduxjs/toolkit";
import { Article } from "@/apis/shared";

interface ArticleTempDataState {
  articleListData: Article[];
  articleListScollTop: number;
  articleListLoading: boolean;
  articleListHasMore: boolean;
  articleListCurrentPage: number;
}

const articleTempDataSlice = createSlice({
  name: "articleTempData",
  initialState: {
    articleListData: [],
    articleListScollTop: 0,
    articleListLoading: false,
    articleListHasMore: true,
    articleListCurrentPage: 1,
  } as ArticleTempDataState,
  reducers: {
    // 保存文章列表数据
    saveArticleListData: (state, actions: { payload: Article[] }) => {
      state.articleListData = actions.payload;
    },
    // 清空文章列表数据
    clearArticleListData: (state) => {
      state.articleListData = [];
    },
    // 保存文章列表滚动条位置
    saveArticleListScollTop: (state, action: { payload: number }) => {
      state.articleListScollTop = action.payload;
    },
    // 清空文章列表滚动条位置
    clearArticleListScollTop: (state) => {
      state.articleListScollTop = 0;
    },
    // 保存文章列表加载状态
    saveArticleListLoading: (state, action: { payload: boolean }) => {
      state.articleListLoading = action.payload;
    },
    // 清空文章列表加载状态
    clearArticleListLoading: (state) => {
      state.articleListLoading = false;
    },
    // 保存文章列表是否有更多数据
    saveArticleListHasMore: (state, action: { payload: boolean }) => {
      state.articleListHasMore = action.payload;
    },
    // 清空文章列表是否有更多数据
    clearArticleListHasMore: (state) => {
      state.articleListHasMore = true;
    },
    // 保存文章列表当前页数
    saveArticleListCurrentPage: (state, action: { payload: number }) => {
      state.articleListCurrentPage = action.payload;
    },
    // 清空文章列表当前页数
    clearArticleListCurrentPage: (state) => {
      state.articleListCurrentPage = 1;
    },
    // 重置文章列表数据
    resetArticleListTempData: (state) => {
      state.articleListData = [];
      state.articleListScollTop = 0;
      state.articleListLoading = false;
      state.articleListHasMore = true;
      state.articleListCurrentPage = 1;
    },
  },
});

// 获取文章列表数据action
const {
  saveArticleListData,
  saveArticleListHasMore,
  saveArticleListLoading,
  saveArticleListScollTop,
  resetArticleListTempData,
  saveArticleListCurrentPage,
} = articleTempDataSlice.actions;

// 获取文章列表数据reducer
const articleTempDataReducer = articleTempDataSlice.reducer;

// 导出action
export {
  saveArticleListData,
  saveArticleListHasMore,
  saveArticleListLoading,
  saveArticleListScollTop,
  resetArticleListTempData,
  saveArticleListCurrentPage,
};

// 默认导出文章列表数据reducer
export default articleTempDataReducer;
